<template>
  <div class="view-fill">
    <div
      v-if="!detailInfo.visible && !modifyInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="采购单汇总单明细"
        :btn-list="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!--  <el-button v-if="canPrint" :plain="true" @click="print"
            >打印</el-button
          > -->
          <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button>

          <el-button v-if="canRevoke" @click="handelMethodRequest('revoke')"
            >撤回
          </el-button>
          <el-button v-if="canRatify" @click="handelMethodRequest('ratify')"
            >批准
          </el-button>
          <el-button v-if="canBreak" @click="handelMethodRequest('stop')"
            >中止
          </el-button>
          <el-button v-if="canSubmit" @click="handelMethodRequest('submit')"
            >提交
          </el-button>
          <el-button v-if="canReject" @click="handelMethodRequest('reject')"
            >整单驳回</el-button
          >
          <el-button v-if="canDoPurch" @click="handelMethodRequest('doPurch')"
            >采购</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>采购汇总单列表</p>
          </div>
          <div class="model-panel-body">
            <new-page-filter :filter-btn="filterOrderInfo.btnList">
              <template v-slot:filter-purch>
                <el-button :disabled="tableRow.status !== 1" @click="add"
                  >添加采购单</el-button
                >
              </template>

              <template v-slot:filter-deletePurchOrder>
                <el-button :disabled="tableRow.status !== 1" @click="remove"
                  >删除采购单</el-button
                >
              </template>
            </new-page-filter>
            <div class="flex_full_item">
              <page-table
                :pager="false"
                :field-list="orderInfo.fieldList"
                :handle="orderInfo.handle"
                v-model:data="orderInfo.data"
                @handleEvent="handleOrderEvent"
              >
                <template v-slot:col-orderNo="scope">
                  <span class="slip-edit" @click="showDetail(scope.row)">{{
                    scope.row.orderNo
                  }}</span>
                </template>
              </page-table>
            </div>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
            <div class="model-tips">
              (证照：<span>近效期</span>
              <span class="model-tips-nearly"></span>
            </div>
            <div class="model-tips">
              <span>过期</span>
              <span class="model-tips-expire"></span>)
            </div>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :check-box="false"
                :default-sort="tableInfo.defaultSort"
                :api="tableInfo.api"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <purch-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :is-special-edit="modifyInfo.isSpecialEdit"
      :orderId="modifyInfo.purchOrderId"
      :table-key="modifyInfo.tableKey"
      @returnModify="returnModify"
    />
    <purch-order-details
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      :orderId="detailInfo.purchOrderId"
    ></purch-order-details>
    <select-order
      v-if="showSelectOrder"
      v-model:show-dialog="showSelectOrder"
      :query="showSelectOrderQuery"
      @callback="callbackOrder"
    ></select-order>
  </div>
</template>

<!-- <script>
import detailPageViewMixin from '@/mixins/detailPageViewMixin'
export default {
  mixins: [detailPageViewMixin],
}
</script> -->

<script setup name="purchOrderSummaryDetailView">
import {
  fatchPurchOrderSummaryId,
  exportPurchOrderSummary,
  purchOrderSummaryDetailCustomizeListAll,
  postPurchOrderSummaryBatchReject,
  postPurchOrderSummaryReject,
  getPurchOrderAll,
  methodPurchOrderSummary,
  purchOrderSummaryAddPurchOrder,
  purchOrderSummaryDeletePurchOrder,
  getPurchOrderSummaryPrint,
} from '@/api/purch'
import { getBusinessKeyById } from '@/api/flowable'
import { getCoreSystemConfigAll } from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
import { orderAffairAll } from '@/api/affair'
import { fatchTemplateByCode } from '@/api/base'
import PurchOrderDetails from '@/views/purch/order/detail'
import PurchOrderModify from '@/views/purch/order/modify'
import SelectOrder from './selectOrder'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'tableRow'])

const tableKey = ref(
  'purchOrderSummaryDetail-com.slip.spd.entity.vo.purch.PurchOrderSummaryDetailVO'
)
const infoList = ref({
  data: {},
  fieldList: [
    { label: '采购汇总单号', value: 'orderNo', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '审批人', value: 'updateUserName', type: 'text' },
    { label: '审批时间', value: 'updateTime', type: 'text' },
    {
      label: '是否寄售',
      value: 'isConsignBusinessValue',
      type: 'text',
      show:
        proxy.$store.state.permission.systemConfig.is_consign_business === 1,
    },
    { label: '是否临采', value: 'temporaryPurchValue', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRow.id,
      },
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [],
  btnList: [],
})
const fullInfo = ref({
  btnList: [],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  fieldList: [],
})
const affairTableInfo = ref({
  api: orderAffairAll,
  query: {
    orderType: 32,
    orderId: props.tableRow.id,
    orgId: props.tableRow.orgId,
    sort: 'operate_time desc',
  },
})
const purchOrderCheckApplicationInfo = ref({
  visible: false,
  title: '通过申购单生成采购单',
  purchApplicationId: null,
})
const systemConfig = ref({})
const filterOrderInfo = ref({
  btnList: [
    {
      value: 'purch',
      type: 'slot',
      show: proxy.$permission('purchOrderSummary:purch'),
    },
    {
      value: 'deletePurchOrder',
      type: 'slot',
      show: proxy.$permission('purchOrderSummary:deletePurchOrder'),
    },
  ],
})
const orderInfo = ref({
  data: [],
  selections: [],
  fieldList: [
    { label: '采购单号', value: 'orderNo', type: 'slot' },
    { label: '部门', value: 'deptName' },
    { label: '创建人', value: 'createUserName' },
    { label: '更新时间', value: 'updateTime' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        type: 'button',
        label: '驳回',
        event: rejectBatch,
        show: proxy.$permission('purchOrderSummary:reject'),
        ifRender: (row) => {
          return row.status === 9
        },
      },
      {
        type: 'button',
        label: '特殊修改',
        event: update,
        show: proxy.$permission('applicationSummary:specialUpdate'),
        ifRender: (row) => {
          return row.status === 12
        },
      },
    ],
  },
})
const detailInfo = ref({
  visible: false,
  data: {},
  purchOrderId: undefined,
})
const modifyInfo = ref({
  visible: false,
  title: '',
  isSpecialEdit: 1,
  purchOrderId: null,
  tableKey:
    'purchOrderDetailModify-com.slip.spd.entity.vo.purch.PurchOrderDetailVO',
})
const showSelectOrder = ref(false)
const showSelectOrderQuery = ref({})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('purchOrderSummary:print') &&
    infoList.value.data.status !== 1
  )
})
const canExcel = computed(() => {
  return (
    proxy.$permission('purchOrderSummary:excel') &&
    infoList.value.data.status !== 1
  )
})
//驳回
const canReject = computed(() => {
  return (
    proxy.$permission('purchOrderSummary:reject') &&
    infoList.value.data.status === 2
  )
})
const canDoPurch = computed(() => {
  return (
    (proxy.$permission('purchOrder:doPurch') &&
      infoList.value.data.status === 3) ||
    infoList.value.data.status === 9
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('purchOrderSummary:submit') &&
    infoList.value.data.status === 1
  )
})
const canRatify = computed(() => {
  return (
    proxy.$permission('purchOrderSummary:ratify') &&
    infoList.value.data.status === 2
  )
})
const canRevoke = computed(() => {
  let type = false
  if (infoList.value.data.status === 2) {
    type = true
  } else if (infoList.value.data.status === 3) {
    if (infoList.value.data.beforeMergeStatus === 3) {
      type = true
    } else {
      type = false
    }
  }
  return proxy.$permission('purchOrderSummary:revoke') && type
})
const canBreak = computed(() => {
  let type = false
  if (infoList.value.data.status === 8 || infoList.value.data.status === 7) {
    type = true
  } else if (infoList.value.data.status === 3) {
    if (infoList.value.data.beforeMergeStatus === 2) {
      type = true
    } else {
      type = false
    }
  }
  return proxy.$permission('purchOrder:stop') && type
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)

setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrderSummary:price'),
      show: false,
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrderSummary:price'),
      show: false,
      hidden: true,
    },
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('purchOrderSummary:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function returnModify() {
  if (props.tableRow.id) {
    getCustomize()
  }
}
function callbackOrder(ids) {
  let params = {
    version: props.tableRow.version,
    id: props.tableRow.id,
    mergeOrderIds: ids,
  }
  purchOrderSummaryAddPurchOrder(params).then((res) => {
    if (res && res.success) {
      getList()
      getMain()
      getPurchOrderList()
      getValueList()
    }
  })
}
function returnBack() {
  emits('returnBack', false)
}
function getList() {
  tableInfo.value.refresh = Math.random()
}

function getMain() {
  fatchPurchOrderSummaryId(props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
    }
  })
}
function getPurchOrderList() {
  getPurchOrderAll({ summaryId: props.tableRow.id }).then((resp) => {
    if (resp && resp.success) {
      orderInfo.value.data = resp.data
    }
  })
}
//导出excel
function exportExcel() {
  exportPurchOrderSummary(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'purchOrderSummaryDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.tableRow.id,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      tempCode: 'purchOrderSummaryDetail',
      orderId: props.tableRow.id,
      orderType: 32,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.tableRow.id,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function getPirntData(temp) {
  let params = {
    tableKey:
      'purchOrderSummaryDetail-com.slip.spd.entity.vo.purch.PurchOrderSummaryDetailVO',
    orderIds: [props.tableRow.id],
  }
  getPurchOrderSummaryPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('purchOrderSummary:price')
      )
    }
  })
}
function getValueList() {
  getCoreSystemConfigAll().then((resp) => {
    if (resp && resp.success) {
      const data = {}
      resp.data.forEach((item) => {
        data[item.systemConfigCode] = item.value
      })
      systemConfig.value = data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiff(new Date(), row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (
      Number(systemConfig.value.license_nearly_effective) >=
      dataDiff >
      0
    ) {
      return 'nearly-row'
    }
  }
  return ''
}
function handelMethodRequest(method) {
  const ids = getSelectionIds(props.tableRow)
  if (method === 'reject') {
    proxy
      .$prompt('请输入驳回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '驳回理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: props.tableRow.id,
          rejectReason: value,
        }
        methodPurchOrderSummary(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else {
    methodPurchOrderSummary(ids, method).then((resp) => {
      if (resp.success) {
        getCustomize()
      }
    })
  }
}
function getSelectionIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map(function (item) {
      return item.id
    })
  }
  return ids
}
function reject() {
  proxy
    .$prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: '驳回理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        id: props.tableRow.id,
        rejectReason: value,
      }
      postPurchOrderSummaryReject(data).then((resp) => {
        if (resp && resp.success) {
          showDialog.value = false
          emits('returnBack', false)
        }
      })
    })
}
function rejectBatch(row) {
  proxy
    .$prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    .then(({ value }) => {
      const data = {
        id: infoList.value.data.id,
        rejectOrderIds: Array.of(row.id),
        rejectReason: value,
      }
      postPurchOrderSummaryBatchReject(data).then((res) => {
        if (res && res.success) {
          getMain()
          getPurchOrderList()
          getList()
          getValueList()
        }
      })
    })
}
function handleOrderEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      orderInfo.value.selections = [...data]
      break
  }
}
function showDetail(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'purchOrder',
  }).then((res) => {
    if (res.success) {
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        detailInfo.value.visible = true
        detailInfo.value.data = { ...row }
        detailInfo.value.purchOrderId = row.id
      }
    }
  })
  
}
function update(row) {
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改采购汇总单'
  modifyInfo.value.purchOrderId = row.id
}
function add() {
  showSelectOrder.value = true
  let ids = orderInfo.value.data.map((a) => a.id)
  showSelectOrderQuery.value = {
    idNotIn: ids.toString(),
    status: orderInfo.value.data[0].beforeMergeStatus,
    temporaryPurch: infoList.value.data.temporaryPurch,
    isConsignBusiness: infoList.value.data.isConsignBusiness,
  }
}
function remove() {
  if (orderInfo.value.selections.length) {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        let ids = orderInfo.value.selections.map((a) => a.id)
        let params = {
          version: props.tableRow.version,
          id: props.tableRow.id,
          mergeOrderIds: ids,
        }
        purchOrderSummaryDeletePurchOrder(params).then((res) => {
          if (res && res.success) {
            getList()
            getMain()
            getPurchOrderList()
            getValueList()
          }
        })
      })
  }
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(_tableInfo.fieldList, data.detail, true)
      _tableInfo.fieldList = obj.fieldList
      _tableInfo.api = purchOrderSummaryDetailCustomizeListAll
      getValueList()
      getMain()
      getPurchOrderList()
      getList()
    }
  })
}
</script>

<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .el-table .nearly-row {
    background: #fceacb;
  }
  .el-table .expire-row {
    background: #f5e4e4;
  }
}
:deep(.caret-wrapper) {
  display: none;
}
</style>
